import React, { useState, useRef, useEffect } from 'react';
import { Modal, Button, Tag, message, Badge, Tooltip } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { history } from 'umi';
import { TableListItem } from '../../Plan/data.d';
import { programDetail } from '../service';
import styles from '../index.less';

const dateFormat = (fmt: string, date: Date) => {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    };
  };
  return fmt;
}

interface PlanComponentProps {
  modalVisible: boolean;
  onCancel: () => void;
  id: number;
}

const PlanModel: React.FC<PlanComponentProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState([]);

  const { modalVisible, onCancel, id } = props;

  useEffect(() => {
    if (modalVisible) {
      setLoading(true);
      new Promise((resolve, reject) => {
        programDetail(id)
          .then((res) => {
            if (res && res.code === 200) {
              let data = res.data;
              const list = data.plans;
              for (let i in list) {
                list[i].index = parseInt(i) + 1;//序号
                list[i].key = list[i].id;
                if (list[i].startDatetime && list[i].endDatetime) {
                  const startDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].startDatetime));
                  const endDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].endDatetime));
                  list[i].startDatetime = startDatetime;
                  list[i].endDatetime = endDatetime;
                  list[i].playDatetime = dateFormat("YYYY-mm-dd", new Date(list[i].startDatetime)) + ' ~ ' + dateFormat("YYYY-mm-dd", new Date(list[i].endDatetime));
                } else {
                  list[i].playDatetime = "一直播放";
                }
              }
              setDataSource(list)
              resolve(true);
            } else {
              message.error('请求失败，' + res.message);
              resolve(false);
            }
            setLoading(false);
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }else{
      setDataSource([]);
    }
  }, [modalVisible]);

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      width: 50,
    },
    {
      title: '计划名称',
      ellipsis: true,
      dataIndex: 'name',
      valueType: 'text',
      width: 150,
      render: (_, record) => (
        record.defaultPlan == 0 ?
          <Tooltip title={record.name}>
            <label style={{ minWidth: 50, maxWidth: 150, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', display: 'block' }}>{record.name}</label>
          </Tooltip> : (
            <Badge count="默认计划" size="small" style={{ background: '#1890ff', color: '#fff' }}>
              <Tooltip title={record.name}>
                <label style={{ minWidth: 50, maxWidth: 150, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', display: 'block' }}>{record.name}</label>
              </Tooltip>
            </Badge>)
      ),
    },
    {
      title: '发布状态',
      dataIndex: 'publishStatus',
      valueType: 'text',
      valueEnum: {
        0: { text: '待发布', status: 'Default' },
        1: { text: '发布中', status: 'Processing' },
        2: { text: '已发布', status: 'Success' },
        3: { text: '部分成功', status: 'Warning' },
        4: { text: '失败', status: 'Error' },
        5: { text: '已结束', status: 'Default' },
      },
      width: 80,
    },
    {
      title: '发布类型',
      dataIndex: 'publishType',
      valueEnum: {
        0: { text: '独立发布' },
        1: { text: '同步发布' },
      },
      width: 80,
    },
    {
      title: '播放模式',
      dataIndex: 'playMode',
      valueEnum: {
        0: { text: '持续播放' },
        1: { text: '按时段播放' },
      },
      width: 100,
    },
    {
      title: '播放日期',
      dataIndex: 'playDatetime',
      valueType: 'text',
      // render: (_, record) => <><span style={{fontSize:12}}>{record.playDatetime}</span></>,
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      hideInSearch: true,
      width: 150,
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{ marginBottom: 5, display: 'inline-block', overflow: 'hidden', whiteSpace: 'pre', textOverflow: 'ellipsis', maxWidth: 130 }}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    // {
    //     title: '更新时间',
    //     dataIndex: 'updateDatetime',
    //     valueType: 'dateTime',
    //     hideInSearch: true, 
    //     render: (_, record) => <><span style={{fontSize:12}}>{record.updateDatetime}</span></>,
    //   },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 50,
      render: (_, record) => (
        <>
          <a
            disabled={localStorage.getItem("authority").indexOf("plan:list") > -1 ? false : true}
            onClick={() => {
              history.push({ pathname: '/plan/list/' });
            }}
          >
            查看
          </a>
        </>
      ),
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="引用计划"
      className={styles.PlanModel}
      width={960}
      centered
      visible={modalVisible}
      onCancel={() => onCancel()}
      footer={[
        <>
          <Button key="cancel" onClick={onCancel}>返回</Button>
        </>
      ]}
    >
      <ProTable<TableListItem>
        size="small"
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={false}
        loading={loading}
        pagination={{ showQuickJumper: true, defaultPageSize: 10 }}
        columns={columns}
        dataSource={dataSource}
        scroll={{ y: 240 }}
      />
    </Modal>
  );
};

export default PlanModel;
